<template>
  <div class="peer">
    <content-header :icon="billingLog" title="Peer Group"></content-header>
    <div class="peer-content">
      <div class="peer-content-panel" :style="{ 'flex-basis': !hideSideBar ? '0' : '283px' }">
        <div v-show="hideSideBar">
          <div style="padding: 16px 16px">
            <el-input placeholder="Search"
                      prefix-icon="el-icon-search"
                      clearable
                      @input="keyWordsChange"
                      v-model="keyWords">
            </el-input>
          </div>
          <save-quick-filter
              type="peerGroup"
              v-if="$refs['filter-condition'] && $refs['sort-condition']"
              :filter="$refs['filter-condition'].filterForm"
              :order="$refs['sort-condition'].clomu_sort" />
          <div class="sort_checkbox_group">
            <div class="sort_checkbox"
                 @click="selectCondit('sort')">
              <sortConditionComponent
                  :conditionItem="conditionItem"
                  @sortChange="listColmSort"
                  :options="options"
                  ref="sort-condition">
              </sortConditionComponent>
            </div>

            <div class="sort_checkbox"
                 @click="selectCondit('filter')">
              <filter-condition
                  :conditionItem="conditionItem"
                  :quickFilter="selectedQuickFilter.id"
                  @filterProjectForm="listColmFilter"
                  ref="filter-condition">
              </filter-condition>
            </div>
          </div>
        </div>
      </div>
      <div class="peer-content-list">
        <div class="peer-content-filter">
          <quick-filter
              type="peerGroup"
              :baseOptions="quickFilter"
              @event:add="handleAdd"
              @event:change="handleChangeQuickFilter"
              v-model="selectedQuickFilter">
            <template v-slot:crumb>
              <Crumb :expand="hideSideBar" @click="hideSideBar = !hideSideBar"/>
            </template>
          </quick-filter>
          <el-button class="newBtn" @click="visible = true" type="primary" size="small">+ New</el-button>
        </div>
        <group-list
            ref="group-list"
            :timeStamp.sync="timeStamp"
            :quickFilter="selectedQuickFilter.id"
            :filter="filterProject"
            @editGroup="editGroup"
            @publicGroup="publicGroup"
            @openCreateGroup="openCreateGroup">
        </group-list>
      </div>
    </div>
    <create-new-group :visible.sync="visible" :groupId.sync="editGroupId" :timeStamp.sync="timeStamp"></create-new-group>
    <z-notice :visible.sync="showNotice" v-bind="noticeObject"></z-notice>
  </div>
</template>

<script>
import billingLog from '@/assets/img/billing.png'
import contentHeader from '@/components/content-header/content-header'
import createNewGroup from '@/views/modules/mspbots/peerGroup/createNewGroup/createNewGroup'
import groupList from '@/views/modules/mspbots/peerGroup/groupList/groupList'
// { SaveQuickFilter, QuickFilterMixins, QuickFilterItem, Crumb }
import QuickFilter, { SaveQuickFilter, Crumb } from '@/components/quick-filter'
import sortConditionComponent from './sort-condition'
import filterCondition from '@/views/modules/mspbots/peerGroup/filter-condition'
import ZNotice from '@/components/storybook/z-dialog-notice'
import { debounce } from 'lodash'
export default {
  name: 'peerGroup',
  components: {
    contentHeader,
    createNewGroup,
    groupList,
    QuickFilter,
    SaveQuickFilter,
    sortConditionComponent,
    filterCondition,
    Crumb,
    ZNotice
  },
  data () {
    return {
      billingLog,
      hideSideBar: true,
      visible: false,
      showNotice: false,
      noticeObject: {
        icon: 'icon_message_alt_check',
        title: 'Are you sure you want to exit this group？',
        info: 'You cannot undo this operation. Please double-check before you proceed.',
        okButton: {
          text: 'Yes',
          type: 'primary'
        },
        closeButton: {
          text: 'Cancel'
        }
      },
      selectedQuickFilter: {
        id: 'my-group',
        name: 'My Group',
        filterJson: {
          filter: {
            status: [1]
          }
        },
        close: false
      },
      quickFilter: [
        {
          id: 'my-group',
          name: 'My Group',
          filterJson: {
            filter: {
              status: [1]
            }
          },
          close: false
        },
        {
          id: 'public-group',
          name: 'Public Group',
          filterJson: {
            filter: {
              properties: ['Public']
            }
          },
          close: false
        }
      ],
      keyWords: '',
      conditionItem: '',
      options: [
        { value: 'name', label: 'Name' }
      ],
      filterProject: {
        name: '',
        'order': [
          { 'field': 'name', 'sort': 'DESC' }
        ],
        'filter': {
          properties: [],
          affiliation: [],
          status: [],
          creator: []
        }
      },
      editGroupId: null,
      timeStamp: null
    }
  },
  async created () {
    await this.emailPeerGroup()
    this.handleChangeQuickFilter(this.selectedQuickFilter)
  },
  mounted () {
    this.$forceUpdate()
  },
  methods: {
    async emailPeerGroup () {
      try {
        let query = this.$route.query.t
        if (query) {
          query = JSON.parse(atob(decodeURIComponent(query)))
          if (this._.toLower(query.email) === this._.toLower(this.$store.state.user.email)) {
            const { acceptPeerGroupUser } = this.$interface.system
            await acceptPeerGroupUser({
              groupId: query.group_id,
              userId: this.$store.state.user.id
            })
          }
        }
      } catch (e) {
        console.log(e)
      }
    },
    selectCondit (val) {
      this.conditionItem = val
    },
    listColmSort (val) {
      this.filterProject.order = val
      this.$refs['group-list'].getData()
    },
    listColmFilter (val) {
      this.filterProject.filter = val
      this.$refs['group-list'].getData()
    },
    keyWordsChange: debounce(function (val) {
      if (this.filterProject.name === val.trim()) {
        return false
      }
      this.isChangeKeyWords = true
      this.filterProject.name = val.trim()
      this.$refs['group-list'].getData()
    }, 1000),
    editGroup (val) {
      this.editGroupId = val
      this.visible = true
    },
    openCreateGroup () {
      this.visible = true
    },
    publicGroup () {
      this.selectedQuickFilter = {
        id: 'public-group',
        name: 'Public Group',
        filterJson: {
          filter: {
            properties: ['Public']
          }
        },
        close: false
      }
      this.handleChangeQuickFilter(this.selectedQuickFilter)
    },
    handleChangeQuickFilter (record = {}) {
      const { filterJson } = record
      try {
        const { get } = this._
        let { filter = {}, order = [] } = filterJson
        this.$nextTick(async () => {
          this.$refs['sort-condition'].clomu_sort = Object.assign({}, this.$refs['sort-condition'].$options.data().clomu_sort, order[0])
          this.$refs['sort-condition'].sort_order = !get(order, '[0].sort') ? false : get(order, '[0].sort') === 'DESC'
          this.$refs['filter-condition'].filterForm = Object.assign({}, this.$refs['filter-condition'].$options.data().filterForm, filter)
          this.filterProject.filter = this.$refs['filter-condition'].filterForm
          this.filterProject.order = [this.$refs['sort-condition'].clomu_sort]
          this.$refs['filter-condition'].filterForms.createdDateModel = this.getTime(get(filter, 'createDate', {}))
          this.$refs['filter-condition'].dataSetFilterNum()
          this.$refs['group-list'].getData(1)
        })
      } catch (error) {
      }
    },
    getTime (data = {}) {
      const {
        from = '',
        to = ''
      } = data
      if (from.length > 0 || to.length > 0) {
        return [from, to]
      }
      return null
    },
    handleAdd (options) {
      if (!this.hideSideBar) {
        this.hideSideBar = true
      }
      if (this.$refs['filter-condition']) {
        this.$refs['filter-condition'].tab = true
      }
    }
  }
}
</script>

<style scoped lang="scss">
.peer {
  &-content {
    display: flex;
    &-panel {
      background: #fff;
      flex-basis: 283px;
      flex-shrink: 0;
      transition: all .2s;
      border-right: 1px solid #00000014;
    }
    &-filter {
      position: relative;
      .newBtn {
        position: absolute;
        right: 16px;
        top: 16px;
      }
    }
  }
}
.peer-content-list {
  background: #ffffff;
  height: calc(100vh - 185px);
  overflow: hidden;
  flex: 1;
}
</style>
